import { IPSDECMUIActionItem, IPSDETBUIActionItem, IPSDEToolbarItem, IPSDEUIAction, IPSSysMap, IPSSysMapItem } from '@ibiz/dynamic-model-api';
import { AppMobMapService } from '../../ctrl-service/app-mob-map-service';
import { ICtrlActionResult, IMobMapCtrlController, IParam, MobMapEvents } from '../../../interface';
import { AppMDCtrlController } from './app-md-ctrl-controller';
import { Util } from '../../../util';
export class MobMapCtrlController extends AppMDCtrlController implements IMobMapCtrlController {
  /**
   * 移动端菜单部件实例对象
   *
   * @type {IPSAppMenu}
   * @memberof MobMapCtrlController
   */
  public controlInstance!: IPSSysMap;

  /**
   * 获取地址需求AMap插件对象
   *
   * @type {*}
   * @memberof MobMapCtrlController
   */
  public geocoder: any;

  /**
   * 当前 window
   *
   * @type {*}
   * @memberof MobMapCtrlController
   */
  public win: any;

  /**
   * 获取选中数据
   *
   * @returns {any[]}
   * @memberof MobMapCtrlController
   */
  public getSelection(): any[] {
    return this.selections;
  }

  /**
   * 地图数据
   *
   * @type {*}
   * @memberof MobMapCtrlController
   */
  public items: Array<any> = [];

  /**
   * 地图数据项模型
   *
   * @type {}
   * @memberof MobMapCtrlController
   */
  public mapItems: any = {};

  /**
   * 默认排序方向
   *
   * @readonly
   * @memberof MobMapCtrlController
   */
  public minorSortDir: any = '';

  /**
   * 默认排序应用实体属性
   *
   * @readonly
   * @memberof MobMapCtrlController
   */
  public minorSortPSDEF: any = '';

  /**
   * 初始化输入数据
   *
   * @param opts 输入参数
   * @memberof MobMapCtrlController
   */
  public initInputData(opts: any) {
    super.initInputData(opts);
    this.isSelectFirstDefault = !!opts?.isSelectFirstDefault;
  }

  /**
   * 多数据部件模型数据加载
   *
   * @memberof MobMapCtrlController
   */
  public async ctrlModelLoad() {
    if (App.isPreviewMode()) {
      return ;
    }
    await super.ctrlModelLoad();
    //  实体服务
    this.ctrlService = new AppMobMapService(this.controlInstance, this.context);
    await this.ctrlService.loaded();
    //  实体fill
    const mapItems: Array<IPSSysMapItem> = this.controlInstance.getPSSysMapItems() || [];
    if (mapItems.length > 0) {
      for (const item of mapItems) {
        await item.getPSAppDataEntity?.()?.fill?.();
        await item.getNavPSAppView?.()?.fill?.();
      }
    }
  }

  /**
   * 部件基础数据初始化
   *
   * @memberof MobMapCtrlController
   */
  public ctrlBasicInit() {
    super.ctrlBasicInit();
  }

  /**
   * 初始化
   *
   * @memberof MobMapCtrlController
   */
  public ctrlInit(args?: any) {
    super.ctrlInit();
    // 绑定this
    this.transformData = this.transformData.bind(this);
    this.refresh = this.refresh.bind(this);
    this.win = window as any;
    // 初始化默认值
    if (this.viewState) {
      this.viewStateEvent = this.viewState.subscribe(
        ({ tag, action, data }: { tag: string; action: string; data: any }) => {
          if (!Object.is(this.name, tag)) {
            return;
          }
          if (Object.is(action, 'load')) {
            this.load(data);
          }
        },
      );
    }
  }

  /**
   * 部件挂载完毕
   *
   * @protected
   * @memberof MobMapCtrlController
   */
  public ctrlMounted(): void {
    super.ctrlMounted();
  }

  /**
   * 刷新
   *
   * @param {*} [args={}]
   * @memberof MobMapCtrlController
   */
  public refresh(opts?: IParam, args?: IParam, showInfo?: boolean, loadding?: boolean): Promise<ICtrlActionResult> {
    this.load(opts);
    return Promise.resolve({ ret: true, data: null });
  }

  /**
   * 地图数据加载
   *
   * @param {*} [data={}] 额外参数
   * @returns {void}
   * @memberof MobMapCtrlController
   */
  public load(data: any = {}): void {
    if (!this.fetchAction) {
      App.getNoticeService().error(`未配置fetchAction行为`);
      return;
    }
    this.items = [];
    const parentData: any = {};
    this.ctrlEvent(MobMapEvents.BEFORE_LOAD, data);
    Object.assign(data, parentData);
    const tempViewParams: any = parentData.viewparams ? parentData.viewparams : {};
    if (this.viewParam) {
      Object.assign(tempViewParams, Util.deepCopy(this.viewParam));
    }
    Object.assign(tempViewParams, data);
    for (const item in this.mapItems) {
      let sort = '';
      if (this.mapItems[item].sort) {
        sort += this.mapItems[item].sort + ',';
      }
      if (sort) {
        sort = sort + 'desc';
        Object.assign(tempViewParams, { sort: sort });
      }
    }
    Object.assign(data, { viewParam: tempViewParams });
    const tempContext: any = Util.deepCopy(this.context);
    this.onControlRequset('load', tempContext, data);
    this.ctrlService.search(this.fetchAction, this.context, data).then(
      (response: any) => {
        if (!response || response.status !== 200) {
          App.getNoticeService().error(response.error?.message || '加载数据异常');
        }
        this.items = response.data;
        this.ctrlEvent(MobMapEvents.LOAD_SUCCESS, this.items);
        // 处理地图所有数据需要一定时间，所以将关闭遮罩放置在地图绘制完成之后
        this.onControlResponse('load', response);
      },
      (response: any) => {
        this.onControlResponse('load', response);
        App.getNoticeService().error(response.error?.message || '加载数据异常');
      },
    );
  }

  /**
   * @description 初始化地图部件上下文菜单模型
   * @memberof MobMapCtrlController
   */
  public initCtrlActionModel() {
    const mapItems = this.controlInstance.getPSSysMapItems() || [];
    const tempModel: any = {};
    if (mapItems?.length > 0) {
      mapItems.forEach((item: IPSSysMapItem) => {
        if (item.getPSDEContextMenu() && item.getPSDEContextMenu()?.getPSDEToolbarItems()) {
          const toobarItems = item.getPSDEContextMenu()?.getPSDEToolbarItems() as IPSDEToolbarItem[];
          if (toobarItems?.length > 0) {
            toobarItems.forEach((toolbarItem: IPSDEToolbarItem) => {
              this.initActionModelItem(toolbarItem, item, tempModel);
            });
          }
        }
      });
    }
    this.actionModel = {};
    Object.assign(this.actionModel, tempModel);
  }

  /**
   * @description 初始化上下菜单项
   * @private
   * @param {IPSDEToolbarItem} toolbarItem 工具栏项
   * @param {IPSSysCalendarItem} item 地图数据项
   * @param {*} tempModel 模型数据
   * @memberof MobMapCtrlController
   */
  private initActionModelItem(toolbarItem: IPSDEToolbarItem, item: IPSSysMapItem, tempModel: any) {
    const tempItem: any = {
      name: toolbarItem.name,
      nodeOwner: item.itemType,
    };
    if (toolbarItem.itemType == 'DEUIACTION') {
      const uiAction: IPSDEUIAction = (toolbarItem as IPSDECMUIActionItem).getPSUIAction() as IPSDEUIAction;
      tempItem.type = item.itemType;
      tempItem.tag = uiAction.id;
      tempItem.visabled = true;
      tempItem.disabled = false;
      if (uiAction?.actionTarget && uiAction?.actionTarget != '') {
        tempItem.actiontarget = uiAction.actionTarget;
      }
      if (uiAction.noPrivDisplayMode) {
        tempItem.noprivdisplaymode = uiAction.noPrivDisplayMode;
      }
      if (uiAction.dataAccessAction) {
        tempItem.dataaccaction = uiAction.dataAccessAction;
      }
    }
    tempModel[`${item.itemType}_${toolbarItem.name}`] = tempItem;
    const toolbarItems = (toolbarItem as IPSDETBUIActionItem)?.getPSDEToolbarItems() || [];
    if (toolbarItems?.length > 0) {
      for (const toolBarChild of toolbarItems) {
        this.initActionModelItem(toolBarChild, item, tempModel);
      }
    }
  }

}
